package com.wash.shoes.request;

import com.ruoyi.common.core.domain.model.BaseModel;
import com.wash.shoes.domain.dy.model.CreateBookDto;
import com.wash.shoes.util.WsRandomUtil;
import lombok.Getter;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Getter
public class DyDelayedOrderRecord extends BaseModel implements Delayed {
    private final long delayTime; // 延迟时间，单位为毫秒

    /**
     * 创建的请求对象
     */
    private CreateBookDto createBookDto;
    /**
     * 对应抖音的accountId
     */
    private String accountId;
    /**
     * 订单号，对应order表的order_no
     */
    private String orderNo;
    /**
     * 抖音的订单号
     */
    private String orderId;
    /**
     * 抖音的item_order_id
     */
    private String itemOrderId;
    /**
     * 重试次数
     */
    private int retryCount;

    public DyDelayedOrderRecord(CreateBookDto createBookDto, String accountId, long delay, String orderNo, String orderId, int retryCount, String itemOrderId) {
        this.accountId = accountId;
        this.orderNo = orderNo;
        this.createBookDto = createBookDto;
        this.orderId = orderId;
        this.delayTime = System.currentTimeMillis() + delay; // 计算延迟结束的时间
        this.retryCount = retryCount;
        this.itemOrderId = itemOrderId;
    }

    public void addRetryCount() {
        ++retryCount;
    }

    /**
     * 刷新外部单号,每次只能用一次
     */
    public void refreshOutNo() {
        createBookDto.setOut_book_no(orderNo + "_" + WsRandomUtil.generateByRandom(10));
    }


    @Override
    public long getDelay(TimeUnit unit) {
        long diff = delayTime - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS); // 返回剩余延迟时间
    }

    @Override
    public int compareTo(Delayed o) {
        DyDelayedOrderRecord that = (DyDelayedOrderRecord) o;
        long diff = this.delayTime - that.delayTime;
        return (diff == 0) ? 0 : ((diff < 0) ? -1 : 1); // 根据延迟时间排序
    }
}